print("进入玩家移动脚本")

UnityEngine = CS.UnityEngine
GameObject = CS.UnityEngine.GameObject
Input = UnityEngine.Input
Camera = UnityEngine.Camera
Vector3 = CS.UnityEngine.Vector3
Time = UnityEngine.Time
Physics = UnityEngine.Physics
RaycastHit = UnityEngine.RaycastHit
App = CS.App
local app = App()

-- 定义 PlayerMove 表
PlayerMove = {}

PlayerMove.tempPoint = Vector3(0, 0, 0)

local characterController = nil
local moveSpeed = 50

-- 初始化 PlayerMove
function PlayerMove:New()
    local obj = {}  -- 创建一个新的表作为实例
    setmetatable(obj, { __index = PlayerMove })  -- 设置元表，使 obj 可以访问 PlayerMove 的方法

    -- 查找玩家对象
    obj.player = GameObject.Find("Player")
    if obj.player == nil then
        error("未找到名为 Player 的游戏对象")
    end

    -- 获取主摄像机
    obj.camera = Camera.main
    if obj.camera == nil then
        error("未找到主摄像机")
    end

    return obj  -- 返回实例化的对象
end

-- 更新方法，监听鼠标点击并移动玩家
function PlayerMove:Update()
    -- 检测鼠标左键点击
    if Input.GetMouseButtonDown(0) then
        -- 获取鼠标点击的屏幕坐标
        local mousePosition = Input.mousePosition

        -- 将屏幕坐标转换为世界坐标
        -- 注意：ScreenToWorldPoint 需要传入一个 z 值，表示摄像机到目标平面的距离
        -- 这里假设玩家在 z = 0 的平面上移动
        local targetPosition = self.camera:ScreenToWorldPoint(Vector3(mousePosition.x, mousePosition.y, 10))
        
        -- 将玩家的位置设置为目标位置
        -- 注意：ScreenToWorldPoint 返回的 z 值可能不为 0，需要根据需求调整
        self.player.transform.position = Vector3(targetPosition.x, targetPosition.y, 0)
    end
end

-- 角色移动到鼠标点击的位置
function PlayerMove:FollowMouse()
    -- 右键点击
    --if CS.UnityEngine.Input.GetMouseButtonDown(0) then
    --
    --    PlayerMove.tempPoint = app:GetTargetPos()
    --    
    --    print("鼠标位置："..PlayerMove.tempPoint.x..","..PlayerMove.tempPoint.y..","..PlayerMove.tempPoint.z)
    --end
    --local step = 10 * CS.UnityEngine.Time.deltaTime
    --self.player.transform.localPosition = CS.UnityEngine.Vector3.MoveTowards(self.player.transform.localPosition, PlayerMove.tempPoint, step)
    --self.player.transform:LookAt(PlayerMove.tempPoint)
end

-- 实例化 PlayerMove
local playerMoveInstance = PlayerMove:New()


function PlayerMove:ManageMovement()

    local moveVector = YaoGan:GetMoveVector() * moveSpeed * Time.deltaTime / Screen.width --获取摇杆移动向量
    print(moveVector)

    --moveVector.z = moveVector.y --y和z位置不同
    --moveVector.y = 0 --让Y位置为0

    local moveDirection = Vector3(moveVector.x, 0, moveVector.y)
    
    
    --if characterController == nil then
    --    characterController = playerMoveInstance.player:GetComponent(typeof(UnityEngine.CharacterController))
    --end
    
    characterController:Move(moveDirection) --角色移动
end

-- 在start中调用PlayerMove的FollowMouse方法
function Start()
    characterController = playerMoveInstance.player:GetComponent(typeof(UnityEngine.CharacterController))
end

-- 在 Update 中调用 PlayerMove 的 Update 方法
function Update()
    --playerMoveInstance:Update()
    --playerMoveInstance:FollowMouse()
    
end
